package cn.com.note.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.RemoteViews;

import com.blankj.utilcode.util.AppUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.com.note.utils.FileUtils;

/**
 * Created by SunFuLin on 2019/6/24.
 */

public class UpdateIntentService extends IntentService {

    public static final String ACTION_UPDATE = "com.apk.update.action.UPDATE";
    public static final String UPDATE_APK = "com.apk.update.action.UPDATE_APK";
    public static final String UPDATE_APK_ERROR = "com.apk.update.action.UPDATE_APK_ERROR";
    public static final String UPDATE_APK_NAME = "app_name";
    public static final String UPDATE_APK_URL = "app_downUrl";
    private NotificationManager mNotificationManager;
    private RemoteViews mRemoteViews;
    private Notification mNotification;
    private Handler mUpdateHandler;
    private String mChannelId = "updateChannel";

    public UpdateIntentService() {
        super("UpdateIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            switch (action) {
                case UpdateIntentService.ACTION_UPDATE:
                    handleActionUpdate(intent);
                    break;
                default:
                    break;
            }
        }
    }

    private void handleActionUpdate(Intent intent) {
        getUpdateHandler();
        beforeUpdateMessage();
        File file = updateIo(intent);
        finishUpdateMessage(file);
    }

    private void getUpdateHandler() {
        mUpdateHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.arg1) {
                    case 2:
                        //发送广播进行更新进度
                        installApk(msg);
                        break;
                    case 3:
                        //发送广播进行更新进度
                        Intent intent2 = new Intent(UPDATE_APK_ERROR);
                        intent2.putExtra("apk_error", true);
                        sendBroadcast(intent2);
                        break;
                }
                return true;
            }
        });
    }

    public File updateIo(Intent intent) {
        File updateFile = FileUtils.getDiskCacheDir(getApplicationContext(), intent.getStringExtra(UPDATE_APK_NAME) + System.currentTimeMillis() + ".apk");
        try {
            URL url = new URL(intent.getStringExtra(UPDATE_APK_URL));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(10000);
            conn.setRequestProperty("Accept-Encoding", "identity");
            conn.connect();
            int length = conn.getContentLength();
            InputStream inputStream = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(updateFile, true);
            int oldProgress = 0;
            byte buf[] = new byte[1024 * 8];
            int currentLength = 0;
            while (true) {
                int num = inputStream.read(buf);
                currentLength += num;
                // 计算进度条位置
                int progress = (int) ((currentLength / (float) length) * 100);
                if (progress > oldProgress) {
                    updatingMessage(progress);
                    oldProgress = progress;
                }
                if (num <= 0) {
                    break;
                }
                fos.write(buf, 0, num);
                fos.flush();
            }
            fos.flush();
            fos.close();
            inputStream.close();
        } catch (Exception e) {
            updateErrorMessage();
            Log.i("updateException", e.toString());
            return null;
        }
        return updateFile;
    }


    private void beforeUpdateMessage() {
        Message message = mUpdateHandler.obtainMessage();
        message.arg1 = 0;
        mUpdateHandler.sendMessage(message);
    }

    private void updatingMessage(int progress) {
        Message message = mUpdateHandler.obtainMessage();
        message.arg1 = 1;
        message.obj = progress;
        mUpdateHandler.sendMessage(message);

        //发送广播进行更新进度
        Intent intent = new Intent(UPDATE_APK);
        intent.putExtra("progress", progress);
        sendBroadcast(intent);
    }

    private void finishUpdateMessage(File file) {
        Message message = mUpdateHandler.obtainMessage();
        message.arg1 = 2;
        message.obj = file;
        mUpdateHandler.sendMessage(message);
    }

    private void updateErrorMessage() {
        Message message = mUpdateHandler.obtainMessage();
        message.arg1 = 3;
        mUpdateHandler.sendMessage(message);
    }


    // 下载完成后打开安装apk界面
    public void installApk(Message msg) {
        File file = (File) msg.obj;
        if (file == null || file.length() == 0) {
            Intent intent = new Intent(UPDATE_APK_ERROR);
            intent.putExtra("apk_error", true);
            sendBroadcast(intent);
            return;
        } else {
            Intent intent = new Intent(UPDATE_APK_ERROR);
            intent.putExtra("apk_finish", true);
            sendBroadcast(intent);
        }
        AppUtils.installApp(file);
    }
}
